<?php
namespace App\Logic\ZiNiao\Work;

use App\Logic\ZiNiao\Api\TasksResults as TasksResultsApi;
use App\Models\ZiNiao\PlansTasks as PlansTasksModel;
use App\Models\ZiNiao\TasksResults as TasksResultsModel;
class TasksResults
{
    public static function exe($taskId = 0){
        $query = PlansTasksModel::query()
            ->where('planStatus','STOP')
            ->where('taskStatus','SUCCESS')
            ->where('status',0);
        if($taskId){
            $query->where('taskId' , $taskId);
        }
        $res = $query->get();
        foreach ($res as $re){
            $status = self::_exe($re->taskId);
            $re->status = $status;
            $re->save();
        }
    }

    private static function _exe($taskId)
    {
        $example = new TasksResultsApi();
        $pageNum = 1;
        $pageSize = 500;
        $bizContent = [
            "taskId" => $taskId,
            "pageNum" => $pageNum,
            "pageSize" => $pageSize,
        ];
        $data = $example->exe($bizContent);
        if(!$data)return 0;
        self::__parseData($data);
        $pageTotal = intval(ceil($data->totalCount / $pageSize));
        while (true){
            if($pageNum == $pageTotal)break;
            $pageNum++;
            $_bizContent = [
                "taskId" => $taskId,
                "pageNum" => $pageNum,
                "pageSize" => $pageSize,
            ];
            $_data = $example->exe($_bizContent);
            if(!$_data)continue;
            self::__parseData($_data);
        }
        return 1;
    }

    private static $_fileTypes = [
        'image'      => 'png|jpg|jpeg|tmp|gif',
        'word'       => 'doc|docx',
        'excel'      => 'xls|xlsx|csv',
        'powerpoint' => 'ppt|pptx',
        'pdf'        => 'pdf',
        'code'       => 'php|js|java|python|ruby|go|c|cpp|sql|m|h|json|html|aspx',
        'archive'    => 'zip|tar\.gz|rar|rpm',
        'txt'        => 'txt|pac|log|md',
        'audio'      => 'mp3|wav|flac|3pg|aa|aac|ape|au|m4a|mpc|ogg',
        'video'      => 'mkv|rmvb|flv|mp4|avi|wmv|rm|asf|mpeg',
    ];

    private static function _getExtension($url)
    {
        $pos = strripos($url,".",-1);
        if(!$pos)return '.xlsx';
        $extension = substr($url,$pos + 1);
        foreach (self::$_fileTypes as $type => $regex) {
            if (preg_match("/^($regex)$/i", $extension) !== 0) {
                return '.'.$extension;
            }
        }
        return '.xlsx';
    }

    private static function __parseData($data){
        foreach ($data->curPage as $_curPage){
            if($_curPage->errorCode != "0" ||
                $_curPage->taskResultType != 'UPLOAD_SUCCESS' ||
                ($_curPage->taskResultType == 'UPLOAD_SUCCESS' && $_curPage->downloadUrl == '无文件'))continue;
            $suffix = self::_getExtension($_curPage->url);
            $fileName = $_curPage->storeName.
                '_'.$_curPage->rpaId.
                ' '.msectimeFormat($_curPage->reportFromDate).'-'.msectimeFormat($_curPage->reportEndDate).
                '_'.$_curPage->siteCode.$suffix;
            TasksResultsModel::query()->updateOrCreate(
                [
                    'taskId' => $_curPage->taskId,
                    'rpaId' => $_curPage->rpaId,
                    'storeName' => $_curPage->storeName,
                    'siteCode' => $_curPage->siteCode,
                ],
                [
                    'downloadUrl' => $_curPage->downloadUrl,
                    'reportFromDate' => $_curPage->reportFromDate,
                    'reportEndDate' => $_curPage->reportEndDate,
                    'fileName' => $fileName,
                ]
            );
        }
    }
}
